package com.study.springbootsecurity.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.study.springbootsecurity.entity.CachedBodyHttpServletRequest;
import com.study.springbootsecurity.exception.BusinessException;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

/**
 * @Description: TODO 读取请求体数据
 * @author: Huangjianyun
 * @date: 2025-06-08 1:10
 */
@Slf4j
public class RequestBodyUtil {
    private final ObjectMapper objectMapper = new ObjectMapper();
    public <T> T getRequestBody(HttpServletRequest request, Class<T> targetType) throws IOException {
        if (request.getContentType() != null && request.getContentType().contains("application/json")) {
            CachedBodyHttpServletRequest wrappedRequest = new CachedBodyHttpServletRequest(request);
            String requestBody = wrappedRequest.getReader().lines().reduce("", String::concat);
            log.info("请求体 JSON 字符串: " + requestBody);

            // 将 JSON 转换为 Java 对象
            T customQuestBody = objectMapper.readValue(requestBody, targetType);
            log.info("转换后的 Java 对象: " + customQuestBody);
            return customQuestBody;
        }
        throw new BusinessException("RequestBodyUtil的获取请求体数据序列化异常");
    }

}
